﻿using System.Web.Security;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.Json;

namespace Jayden.Dll.Web.Controls.Admin
{
	public class DeleteRoleForm : Form
	{
		private Select m_Roles;
		private Button m_DeleteRoles;

		public override void Load(System.Xml.XmlNode node, HtmlControlLoader loader)
		{
			base.Load(node, loader);
			if (Id == null)
				Id = "deleteRoleForm";
			m_Roles = GetFormElement<Select>("roles");
			m_DeleteRoles = GetFormElement<Button>("deleteRoles", "command");
			FillFromProvider();
		}

		private void FillFromProvider()
		{
			m_Roles.Clear();
			foreach (string roleName in Roles.GetAllRoles())
				m_Roles.AddOption(roleName, roleName);
		}

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			RoleProviderDiv.RoleCommandHandler roleHandler = context.HandlerManager.GetHandler<RoleProviderDiv.RoleCommandHandler>();
			roleHandler.RolesCreated += new RoleProviderDiv.OnRolesCreated(RolesCreated);
			roleHandler.RolesDeleted += new RoleProviderDiv.OnRolesDeleted(RolesDeleted);
			base.ProcessHtmlRequest(context);
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			RoleProviderDiv.RoleCommandHandler roleHandler = context.HandlerManager.GetHandler<RoleProviderDiv.RoleCommandHandler>();
			roleHandler.RolesCreated += new RoleProviderDiv.OnRolesCreated(RolesCreated);
			roleHandler.RolesDeleted += new RoleProviderDiv.OnRolesDeleted(RolesDeleted);
			base.ProcessJsonRequest(context);
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);
			string id = Id;
			context.Js[id].AppendAjaxSubmit(this, m_DeleteRoles);
			context.Js[id].AppendAjaxHtmlHandler(m_Roles, false, false);
		}

		void RolesDeleted(HttpHandlerContext context, string[] roles)
		{
			FillFromProvider();
			if (context.Json != null)
			{
				JsonObject select = new JsonObject();
				select.Add("html", m_Roles.ToInnerHtml(context.Translator));
				context.Json.Add(m_Roles.Id, select);
			}
		}

		void RolesCreated(HttpHandlerContext context, string[] roles)
		{
			FillFromProvider();
			if (context.Json != null)
			{
				JsonObject select = new JsonObject();
				select.Add("html", m_Roles.ToInnerHtml(context.Translator));
				context.Json.Add(m_Roles.Id, select);
			}
		}
	}
}
